import { reactive, onMounted } from 'vue'
import { format } from 'date-fns'
import { parseTime } from '@/common/common'
import { useRouter } from 'vue-router'
import { TaskDefined } from '@/service/modules/task-manage/types'
import { delTaskReq, findTasksReq } from '@/service/modules/task-manage'

export function useTable() {
  const router = useRouter()

  const state = reactive({
    page: 1,
    limit: 10,
    count: 0,
    searchParam: {
      name: '',
      taskTypes: ['DATAX']
    },
    list: [],
    loading: false,
    currentRecord: {} as TaskDefined,
    modTasktModalShow: false
  })

  const getList = async () => {
    if (state.loading) return
    state.loading = true

    const { data, count } = await findTasksReq({
      page: state.page,
      limit: state.limit,
      name: state.searchParam.name,
      taskTypes: state.searchParam.taskTypes + ''
    })
    state.loading = false
    if (!data) throw Error()
    state.list = data.map((record: TaskDefined) => {
      record.createTime = record.createTime
        ? format(parseTime(record.createTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      record.updateTime = record.updateTime
        ? format(parseTime(record.updateTime), 'yyyy-MM-dd HH:mm:ss')
        : ''
      return record
    })
    state.count = count
  }

  const updateList = () => {
    if (state.list.length === 1 && state.page > 1) {
      --state.page
    }
    getList()
  }

  const openTaskDetailTab = (id: number, name: string) => {
    router.push({
      path: '/taskManage/taskDetail',
      query: {
        tab: `${name} ` + window.$t('taskManage.taskDetail'),
        tabName: 'TaskDetailTab',
        taskDefinedId: id
      }
    })
  }
  const delTask = async (id: number, name: string) => {
    window.$dialog.warning({
      title: window.$t('dialog.warningTitle'),
      content: window.$t('taskManage.delTaskTips') + name,
      positiveText: window.$t('dialog.positiveText'),
      negativeText: window.$t('dialog.negativeText'),
      onPositiveClick: async () => {
        const res = await delTaskReq({ taskId: id })
        if (res.resp_code === 0) {
          getList()
        }
      }
    })
  }

  const onOperationClick = (
    data: { rowData: TaskDefined },
    type: 'modTask' | 'delTask' | 'openTaskDetailTab'
  ) => {
    state.currentRecord = data.rowData
    switch (type) {
      case 'modTask':
        state.modTasktModalShow = true
        break
      case 'delTask':
        delTask(data.rowData.id, data.rowData.name)
        break
      case 'openTaskDetailTab':
        openTaskDetailTab(data.rowData.id, data.rowData.name)
        break
    }
  }

  const changePage = (page: number) => {
    state.page = page
    getList()
  }

  const changePageSize = (limit: number) => {
    state.page = 1
    state.limit = limit
    getList()
  }

  onMounted(() => {
    getList()
  })

  return {
    state,
    changePage,
    changePageSize,
    updateList,
    onOperationClick
  }
}
